<!--
 *Author：jxx
 *Date：{Date}
 *Contact：283591387@qq.com
 *业务请在@/extension/mes/mes/ProductTask.jsx或ProductTask.vue文件编写
 *新版本支持vue或【表.jsx]文件编写业务,文档见:https://doc.volcore.xyz/docs/view-grid、https://doc.volcore.xyz/docs/web
 -->
<template>
    <div class="grid">
        <view-grid ref="grid" :columns="columns" :detail="detail" :details="details" :editFormFields="editFormFields"
            :editFormOptions="editFormOptions" :searchFormFields="searchFormFields" :searchFormOptions="searchFormOptions"
            :table="table" :extend="extend" :onInit="onInit" :onInited="onInited" :searchBefore="searchBefore"
            :searchAfter="searchAfter" :addBefore="addBefore" :updateBefore="updateBefore" :delBefore="delBefore"
            :rowClick="rowClick" :modelOpenBefore="modelOpenBefore" :modelOpenAfter="modelOpenAfter"
            :detailSortEnd="detailSortEnd">
            <!-- 自定义组件数据槽扩展，更多数据槽slot见文档 -->
            <template #gridHeader>
            </template>
            <template #gridFooter>
                <div v-if="route.name == 'ProductTask'" rou class="productTaskProcess">
                    <productTaskProcess ref="productTaskProcessRef"></productTaskProcess>
                </div>
            </template>
        </view-grid>
    </div>
    <SelectMaterial ref="materialRef" @onSelectMaterial="onSelectMaterial"></SelectMaterial>
    <SelectBom ref="bomRef" @onSelectBom="onSelectBom"></SelectBom>
    <SelectProcess ref="productProcessRef" @onSelectProductProcess="onSelectProductProcess"></SelectProcess>
    <SelectTechnologicalProcess ref="techProcessRef" @onSelectTechProcess="onSelectTechProcess">
    </SelectTechnologicalProcess>
</template>
<script setup lang="jsx">
import productTaskProcess from './ProductTaskProcess.vue'
import SelectMaterial from './ProductTaskSelectMaterial.vue'
import SelectBom from './ProductTaskSelectBom.vue'
import SelectProcess from './ProductTaskSelectProcess.vue'
import SelectTechnologicalProcess from './ProductTaskSelectTechnologicalProcess.vue'
import extend from "@/extension/mes/mes/ProductTask.jsx";
import viewOptions from './ProductTask/options.js'
import { ref, reactive, getCurrentInstance, watch, onMounted } from "vue";
import { useRoute } from 'vue-router'

const route = useRoute()
const grid = ref(null);
const { proxy } = getCurrentInstance()
//http请求，proxy.http.post/get
const { table, editFormFields, editFormOptions, searchFormFields, searchFormOptions, columns, detail, details } = reactive(viewOptions())
const productTaskProcessRef = ref();

let gridRef;//对应[表.jsx]文件中this.使用方式一样
const materialRef = ref()
const bomRef = ref()
const productProcessRef = ref()
const techProcessRef = ref()

//生成对象属性初始化
const onInit = async ($vm) => {
    gridRef = $vm;

    //期初生产任务单，默认只加载期初单据
    if (route.query.billType == '2') {
        gridRef.searchFormFields.BillType = 2
    }


    gridRef.details[0].sortable = true
    gridRef.details[0].pagination = {
        sortName: "ProcessSeq",
        order: "asc", //排序方式
    };
    proxy.base.setItem('getTaskSelectRow', () => {
        return gridRef.getTable(true).getSelected();
    })

    //设置弹出框编辑宽度
    // gridRef.boxOptions.width = 1100
    //启用明细表排序
    gridRef.detailOptions.sortable = true

    gridRef.detailOptions.pagination.sortName = "ProcessSeq";  //明细表排序字字段
    gridRef.detailOptions.pagination.order = "asc"; //明细表排序方式desc或者asc

    //与jsx中的this.xx使用一样，只需将this.xx改为gridRef.xx
    //更多属性见：https://doc.volcore.xyz/docs/view-grid
    const materialOption = gridRef.getFormOption("MaterialNo");
    materialOption.readonly = true;
    materialOption.extra = {
        icon: 'el-icon-zoom-out', //显示图标
        text: '选择', //显示文本
        style: 'color: #3a8ee6;font-size: 13px;cursor: pointer;',
        //触发事件
        click: (item) => {
            materialRef.value.open();
        }
    };

    const bomOption = gridRef.getFormOption("BomNo");
    bomOption.readonly = true;
    bomOption.extra = {
        icon: 'el-icon-zoom-out', //显示图标
        text: '选择', //显示文本
        style: 'color: #3a8ee6;font-size: 13px;cursor: pointer;',
        //触发事件
        click: (item) => {
            if (gridRef.editFormFields.MaterialNo == null || gridRef.editFormFields.MaterialNo == "") {
                return proxy.$message.error("请选择物料！");
            }
            bomRef.value.open(gridRef.editFormFields.MaterialId);
        }
    };

    const technologicalProcessOption = gridRef.getFormOption("TechnologicalProcessNo");
    technologicalProcessOption.readonly = true;
    technologicalProcessOption.extra = {
        icon: 'el-icon-zoom-out', //显示图标
        text: '选择', //显示文本
        style: 'color: #3a8ee6;font-size: 13px;cursor: pointer;',
        //触发事件
        click: (item) => {
            if (gridRef.editFormFields.MaterialNo == null || gridRef.editFormFields.MaterialNo == "") {
                return proxy.$message.error("请选择物料！");
            }
            techProcessRef.value.open(gridRef.editFormFields.MaterialId);
        }
    };


}

//生成对象属性初始化后,操作明细表配置用到
const onInited = async () => {
    columns.forEach(x => {
        //开启表头过滤
        x.filterData = true;
    })
    
    gridRef.height = gridRef.height - 310;

    if (gridRef.height < 200) {
        gridRef.height = 200;
    }
    gridRef.buttons.splice(2, 0, {
        name: '生成子任务', //按钮名称
        icon: 'el-icon-document', //按钮图标:组件示例->图标
        //primary、success、warning、error、info、text、danger
        type: 'primary',
        plain: true,
        onClick: () => {
            createNextTask();
        }
    })
    gridRef.buttons.splice(2, 0, {
        name: '生成用料清单', //按钮名称
        icon: 'el-icon-document', //按钮图标:组件示例->图标
        //primary、success、warning、error、info、text、danger
        type: 'primary',
        plain: true,
        onClick: () => {
            createMaterialList();
        }
    })
    gridRef.buttons.splice(2, 0, {
        name: '结案', //按钮名称
        icon: 'el-icon-document', //按钮图标:组件示例->图标
        //primary、success、warning、error、info、text、danger
        type: 'primary',
        plain: true,
        onClick: () => {
            closureClick();
        }
    })
    gridRef.buttons.splice(99, 0, {
        name: '反结案', //按钮名称
        icon: 'el-icon-document', //按钮图标:组件示例->图标
        //primary、success、warning、error、info、text、danger
        type: 'primary',
        plain: true,
        onClick: () => {
            unClosureClick();
        }
    })

    //期初生产任务单，隐藏其他按钮
    if (route.query.billType == '2') {

        gridRef.buttons.forEach(x => {//name改为要隐藏的按钮名字
            if (x.name == '生成用料清单'
                || x.name == '生成子任务'
            ) {
                x.hidden = true;
            }
        })
    }




    //选择【工序】
    const processCodeCol = gridRef.details[0].columns.find((x) => {
        return x.field == 'ProcessCode'
    })
    processCodeCol.render = (h, { row, column, index }) => {

        return (
            <div>
                <el-button
                    link
                    onClick={($e) => {
                        productProcessRef.value.open(row)
                    }}
                    class="el-icon-search"
                    style="color: #2196F3;cursor: pointer;"
                ></el-button>

                <span style="margin-right:5px">{row.ProcessCode}</span>
            </div>
        )

    }

}

const searchBefore = async (param) => {
    //界面查询前,可以给param.wheres添加查询参数
    //返回false，则不会执行查询

    return true;
}
const searchAfter = async (rows, result) => {
    return true;
}
const addBefore = async (formData) => {
    //新建保存前formData为对象，包括明细表，可以给给表单设置值，自己输出看formData的值
    return true;
}
const updateBefore = async (formData) => {
    //编辑保存前formData为对象，包括明细表、删除行的Id
    return true;
}
const delBefore = (ids, rows) => { //查询界面的表删除前 ids为删除的id数组,rows删除的行
    let isDeleted = true
    let detailRows = productTaskProcessRef.value.$refs.grid.getTable(true).rowData

    rows.forEach(row => {
        if (row.AuditStatus == 1) {
            isDeleted = false
            proxy.$message.error(row.BillNo + "已审核不允许删除！");
            return isDeleted;
        }
    });

    for (let i = 0; i < detailRows.length; i++) {
        const detailRow = detailRows[i];
        if (detailRow.ProductNoticeNo != null && detailRow.ProductNoticeNo != "") {
            isDeleted = false
            proxy.$message.error("【" + detailRow.ProcessCode + detailRow.ProcessName + "】该任务工序明细已生成【生产通知】不允许删除！");
            return isDeleted;
        }
    }

    return isDeleted;//返回false，界面上不会显示
}
const rowClick = ({ row, column, event }) => {
    //查询界面点击行事件
    // grid.value.toggleRowSelection(row); //单击行时选中当前行;
    //点击行清除选中的行(用于下面明细表判断)
    grid.value.clearSelection();
    //点击行默认选中
    grid.value.toggleRowSelection(row); //单击行时选中当前行;
    //加载明细表
    productTaskProcessRef.value.$refs.grid.search();
}
const modelOpenBefore = async (row) => {//弹出框打开后方法
    return true;//返回false，不会打开弹出框
}
const modelOpenAfter = (row) => {
    //弹出框打开后方法,设置表单默认值,按钮操作等
    gridRef.setFormReadonly(false);

    if (gridRef.currentAction == 'Add') {
        if (route.query.billType == '2') {
            gridRef.editFormFields.BillType = 2
        }
        else {
            gridRef.editFormFields.BillType = 1
        }
        gridRef.editFormFields.BillDate = proxy.base.getDate()
        gridRef.editFormFields.CompleteStatusId = 0
        gridRef.editFormFields.ClosureStatusId = 1
        gridRef.editFormFields.IsCreateMaterialList = 0
        gridRef.editFormFields.ExigenceId = 0
        gridRef.boxButtons.forEach((btn) => {
            if (btn.name == '保存') {
                btn.hidden = false;
                //或者设置只读
                // btn.readonly = true;
            }

        });
    }
    else {
        if (row.AuditStatus != 0 && row.AuditStatus != null) {
            gridRef.setFormReadonly(true);
            gridRef.boxButtons.forEach((btn) => {
                if (btn.name == '保存') {
                    btn.hidden = true;
                    //或者设置只读
                    // btn.readonly = true;
                }

            });
        }
        else {
            gridRef.boxButtons.forEach((btn) => {
                if (btn.name == '保存') {
                    btn.hidden = false;
                    //或者设置只读
                    // btn.readonly = true;
                }
            });

        }
    }
}
const onSelectMaterial = (rows) => {
    editFormFields.MaterialId = rows[0].MaterialId;
    editFormFields.MaterialNo = rows[0].Code;
    editFormFields.MaterialName = rows[0].Name;
    editFormFields.Spec = rows[0].Spec;
    editFormFields.MaterialTypeId = rows[0].MaterialTypeId;
    editFormFields.UnitId = rows[0].MaterialUnitId;
    //这里还可以给其他字段设置值editFormFields.字段=
}
const onSelectBom = (rows) => {

    editFormFields.BomId = rows[0].BomId;
    editFormFields.BomNo = rows[0].BillNo;
    let url = 'api/MaterialsBom/getBomByInfo';

    proxy.http.post(url, rows[0]).then((result) => {
        // 刷新主表列表
        gridRef.getTable("ProductMaterialList").rowData = []
        result.materialBomDetail.forEach(bomDetail => {
            gridRef.getTable("ProductMaterialList").addRow({
                MaterialId: bomDetail.materialId,
                MaterialNo: bomDetail.materialNo,
                MaterialName: bomDetail.materialName,
                Spec: bomDetail.Spec,
                MaterialTypeId: bomDetail.materialTypeId,
                UnitId: bomDetail.unitId,
                IsBackflush: bomDetail.isBackflush,
                DepartmentId: bomDetail.departmentId,
                NextBomId: bomDetail.nextBomId,
                NextBomNo: bomDetail.nextBomNo,
                IsCriticalParts: bomDetail.isCriticalParts,
                AttritionRate: bomDetail.attritionRate,
                UseMaterialQty: 0,
                UnitQty: bomDetail.unitQty,

            })

        });

    });


}
const onSelectTechProcess = (rows) => {
    editFormFields.BomId = rows[0].BomId;
    editFormFields.BomNo = rows[0].BomNo;
    editFormFields.TechnologicalProcessId = rows[0].TechnologicalProcessId;
    editFormFields.TechnologicalProcessNo = rows[0].BillNo;
    let url = 'api/MaterialsBom/getTechnologicalProcessByInfo';

    gridRef.getTable("ProductTaskProcess").rowData = []
    gridRef.getTable("ProductMaterialList").rowData = []
    proxy.http.post(url, rows[0]).then((result) => {
        // 刷新主表列表
        result.processDetail.forEach(item => {
            gridRef.getTable("ProductTaskProcess").addRow({
                ProductProcessId: item.productProcessId,
                ProcessCode: item.processCode,
                ProcessName: item.processName,
                ProcessTypeId: item.processTypeId,
                IsLasted: item.isLasted,
                UpProcessCode: item.upProcessCode,
                DepartmentId: item.departmentId,
                DeviceId: item.deviceId,
                ProductionGroupId: item.productionGroupId,
                WorkerId: item.workerId,
                IsOutSource: item.isOutSource,
                SupplyId: item.supplyId,
                ReportWorkTypeId: item.reportWorkTypeId,
                IsDispatch: item.isDispatch,
                ProcessSeq: item.processSeq,
                WorkHourPrice: item.workHourPrice,
                WorkQtyPrice: item.workQtyPrice,
                PriceTypeId: item.priceTypeId,

            })

        });
        result.processBomDetail.forEach(bomDetail => {

            gridRef.getTable("ProductMaterialList").addRow({
                MaterialId: bomDetail.materialId,
                MaterialNo: bomDetail.materialNo,
                MaterialName: bomDetail.materialName,
                Spec: bomDetail.Spec,
                MaterialTypeId: bomDetail.materialTypeId,
                UnitId: bomDetail.unitId,
                IsBackflush: bomDetail.isBackflush,
                DepartmentId: bomDetail.departmentId,
                NextBomId: bomDetail.nextBomId,
                NextBomNo: bomDetail.nextBomNo,
                IsCriticalParts: bomDetail.isCriticalParts,
                AttritionRate: bomDetail.attritionRate,
                UseMaterialQty: 0,
                UnitQty: bomDetail.unitQty,

            })

        });

    });


}

//选择工序回调
const onSelectProductProcess = (rows) => {
    let rowData = gridRef.getTable('ProductTaskProcess').rowData
    //更新明细中最后一个行是否末级工序
    // //写入明细表
    // rowData.push(...rows)
    rowData.map((row, index) => {
        if (row.ProductProcessId != null) {
            row.ProcessSeq = index + 1
            if (rowData.length == index + 1) {
                row.IsLasted = 1
            }
            else {
                row.IsLasted = 0
            }
        }
    });

}

// 创建用料清单
const createMaterialList = async () => {
    //可以获取选中的行数据
    let rows = gridRef.getSelectRows();
    if (!rows.length) {
        return proxy.$message.error('请选择生产任务');
    }
    let isAuditStatus = true
    rows.forEach((item, index) => {
        if (item.AuditStatus == 0 || item.AuditStatus == null) {
            isAuditStatus = false
        }
    })
    if (!isAuditStatus) {
        proxy.$message.error("该生产任务未审核！");
        return
    }
    let isCreateMaterialList = false
    let list = []
    rows.forEach((item, index) => {
        if (item.IsCreateMaterialList == 1) {
            isCreateMaterialList = true
            list.push(item.BillNo)
        }
    })
    if (isCreateMaterialList) {
        proxy.$message.error(list.toString() + "已创建用料清单！");
        return
    }
    let url = 'api/ProductTask/createMaterialList';
    proxy.http.post(url, rows).then((result) => {
        proxy.$message.success("创建成功");
        gridRef.search();
    });
}

const unClosureClick = async () => {
    //可以获取选中的行数据
    let rows = gridRef.getSelectRows();

    let url = 'api/ProductTask/unTaskClosure';
    proxy.http.post(url, rows).then((result) => {
        proxy.$message.success("反结案成功！");
        gridRef.search();
    });
}
const createNextTask = async () => {
    let rows = gridRef.getSelectRows();
    if (!rows.length) {
        return proxy.$message.error('请选择生产任务');
    }
    rows.forEach((item, index) => {
        if (item.AuditStatus == 0 || item.AuditStatus == null) {
            proxy.$message.error("该生产任务未审核！");
            return
        }
    })

    let url = 'api/ProductTask/createNextTask';
    proxy.http.post(url, rows).then((result) => {
        proxy.$message.success("创建成功");
        gridRef.search();
    });
}
const detailSortEnd = (newIndex, rows, oldIndex) => {
    //拖动后对表的字段重新排序
    rows.forEach((x, index) => {
        if (rows.length == index + 1) {
            x.IsLasted = 1
        }
        else {
            x.IsLasted = 0
        }
        x.ProcessSeq = index + 1
    })
}
//监听表单输入，做实时计算
//watch(() => editFormFields.字段,(newValue, oldValue) => {	})
//对外暴露数据
defineExpose({})
</script>
